package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.ClazzMapper;
import com.itheima.pojo.Clazz;
import com.itheima.pojo.Emp;
import com.itheima.pojo.PageResult;
import com.itheima.service.ClazzService;
import com.itheima.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ClazzServiceImpl extends ServiceImpl<ClazzMapper, Clazz> implements ClazzService {
    @Autowired
    private EmpService empService;
    /**
     * 条件分页查询班级信息
     *
     * @param name
     * @param begin
     * @param end
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public PageResult<Clazz>  listClass(String name, LocalDate begin, LocalDate end, int page, int pageSize) {
        //基本信息
        Page<Clazz> page1 = new Page<>(page,pageSize);
        page1.addOrder(OrderItem.desc("update_time"));
        page1 = lambdaQuery().like(name !=null && !name.isEmpty(),Clazz::getName,name)
                .between(begin !=null && end !=null,Clazz::getEndDate,begin,end)
                .page(page1);

        List<Clazz> clazzList = page1.getRecords();
        //映射到员工id
        List<Integer> empids = clazzList.stream().map(clazz -> clazz.getMasterId()).collect(Collectors.toList());
//        Integer empid= clazzList.stream().map(clazz -> clazz.getMasterId()).findFirst().get();
        if(!empids.isEmpty()){
            //根据id查询部门信息
            List<Emp> emps =  empService.listByIds(empids);
            //遍历集合，获取班级对应的班主任部门名称
            clazzList.forEach(clazz -> {
                //查询班主任名称
                emps.forEach(emp -> {
                    if(clazz.getMasterId()!=null && clazz.getMasterId().equals(emp.getId())){
                        clazz.setMasterName(emp.getName());
                    }
                });
                //查询status
                LocalDate now =LocalDate.now();
                if(now.isAfter(clazz.getEndDate())){
                    clazz.setStatus("已节课");
                }
                if(now.isBefore(clazz.getBeginDate())){
                    clazz.setStatus("未开课");
                }
                if(now.isBefore(clazz.getEndDate())&&now.isAfter(clazz.getBeginDate())){
                    clazz.setStatus("在读");
                }
            });
        }
        return new PageResult<>(page1.getTotal(),clazzList);
    }
}
